package com.xrkj.b2c.utils;

import java.util.Calendar;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.apache.log4j.Logger;

/**
 * 
 * <B>系统名称：</B><BR>
 * <B>模块名称：</B><BR>
 * <B>中文类名：</B>邮件工具类<BR>
 * <B>概要说明：</B><BR>
 * @author 赵子靖
 * @since 2018年07月15日
 */
public class MailUtils {
	
	 private Logger logger=Logger.getLogger(MailUtils.class);
	 
	 @SuppressWarnings("static-access")  
	 public static boolean sendMessage(String smtpHost, String from,  
            String fromUserPassword, String to, String subject,  
            String messageText, String messageType){  
		 boolean status=false;
		 try{
			 // 第一步：配置javax.mail.Session对象  
		        Properties props = new Properties();  
		        props.put("mail.smtp.host", smtpHost);  
		        props.put("mail.smtp.starttls.enable","true");//使用 STARTTLS安全连接  
		        //props.put("mail.smtp.port", "25");             //google使用465或587端口  
		        props.put("mail.smtp.auth", "true");        // 使用验证  
		        //props.put("mail.debug", "true");  
		        Session mailSession = Session.getInstance(props,new MyAuthenticator(from,fromUserPassword));  
		  
		        // 第二步：编写消息  
		  
		        InternetAddress fromAddress = new InternetAddress(from);  
		        InternetAddress toAddress = new InternetAddress(to);  
		  
		        MimeMessage message = new MimeMessage(mailSession);  
		  
		        message.setFrom(fromAddress);  
		        message.addRecipient(RecipientType.TO, toAddress);  
		  
		        message.setSentDate(Calendar.getInstance().getTime());  
		        message.setSubject(subject);  
		        message.setContent(messageText, messageType);  
		  
		        // 第三步：发送消息  
		        Transport transport = mailSession.getTransport("smtp");  
		        transport.connect(smtpHost,"706340089", fromUserPassword);  
		        transport.send(message, message.getRecipients(RecipientType.TO));  
		        status=true;
		 }catch(Exception e){
			 e.printStackTrace();
		 }
       return status;
    }  
	  
//    public static void main(String[] args) {  
//        try {  
//        	MailUtils.sendMessage("smtp.qq.com", "706340089@qq.com",  
//                    "ilgkxpnzgdnbbfab", "365114869@qq.com", "测试",  
//                    "第一个测试",  
//                    "text/html;charset=utf-8");  
//        } catch (MessagingException e) {  
//            e.printStackTrace();  
//        }  
//    }  
}
